package root.electronclass.electronclass.grade.repository

import android.util.Log
import root.electronclass.electronclass.mvp.base.BaseResponse
import root.electronclass.electronclass.mvp.base.data
import root.electronclass.electronclass.mvp.base.isSuccessful
import root.electronclass.electronclass.mvp.entity.ApiException
import root.electronclass.electronclass.mvp.rest.ClassApi
import root.electronclass.electronclass.mvp.rest.RestManager
import root.electronclass.electronclass.ext.toDateYyyyMMdd
import root.electronclass.electronclass.ext.toDateYyyyMMddHHmmss
import root.electronclass.electronclass.grade.model.*
import root.electronclass.electronclass.grade.viewmodel.WeekType
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.Calendar

/**
 *
 * @author Lokiy
 * @date 2023/2/4 13:58
 */
object ClassRepository {


    /**
     * 获取班级通知
     */
    suspend fun getClassNotification(pageIndex: Int, type: Int, key: String? = ""): List<ClassNotification> = withContext(Dispatchers.IO) {
        val baseResponse = RestManager.getInstance().classRest().getClassNoticeList(NoticeQuery(pageNo = pageIndex, title = key ?: "", type = type))
        baseResponse.let {
            check(it)
            it.data.records
        }
    }

    /**
     * 获取班级通知
     */
    suspend fun getClassHonor(pageIndex: Int, type: Int, key: String? = ""): List<ClassHonor> = withContext(Dispatchers.IO) {
        val baseResponse = RestManager.getInstance().classRest().getClassHonorList(HonorQuery(pageNo = pageIndex, search = key ?: "", type = type))
        baseResponse.let {
            check(it)
            it.data.records
        }
    }

    /**
     * 获取班级通知
     */
    suspend fun getClassRecord(pageIndex: Int, type: Int, key: String? = ""): List<ClassRecord> = withContext(Dispatchers.IO) {
        val baseResponse = RestManager.getInstance().classRest().getClassRecordList(RecordQuery(pageNo = pageIndex, search = key ?: "", type = type))
        baseResponse.let {
            check(it)
            it.data.records
        }
    }

    /**
     * 获取班级通知
     */
    suspend fun getClassCurriculum() = withContext(Dispatchers.IO) {
        val calendar = Calendar.getInstance()
        //1 周日 2周一 3周二 4周三
        val dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK)
        if (dayOfWeek >= 2) {
            calendar.add(Calendar.DAY_OF_YEAR, -(dayOfWeek - 2))
        } else {
            calendar.add(Calendar.DAY_OF_YEAR, -6)
        }
        calendar.add(Calendar.DAY_OF_YEAR, -7)
        val startDate = calendar.timeInMillis.toDateYyyyMMdd()
        calendar.add(Calendar.DAY_OF_YEAR, 20)
        val endDate = calendar.timeInMillis.toDateYyyyMMdd()
        calendar.add(Calendar.DAY_OF_YEAR, -20)

        RestManager.getInstance().classRest().getClassCurriculum(startDate, endDate).let {
            check(it)
            it.data to calendar
        }
    }

    /**
     * 获取班级值日项
     */
    suspend fun getClassRota(selectDate: String): List<ClassRotaItem> = withContext(Dispatchers.IO) {
        Log.e("XXX", "----------getClassRota加载日期--$selectDate-----")
        RestManager.getInstance().classRest().getClassRotaByDate(selectDate).let {
            check(it)
            it.data
        }
    }

    /**
     * 获取班级通知
     */
    suspend fun getClassHomework(selectDate: String): List<ClassHomeworkItem> = withContext(Dispatchers.IO) {
        Log.e("XXX", "----------getClassHomework加载日期--$selectDate-----")
        RestManager.getInstance().classRest().getHomeworkByDate(selectDate).let {
            check(it)
            it.data
        }
    }

    /**
     * 获取班级通知
     */
    suspend fun getClassHomeworkStatistical(dayOfWeek: Int, type: WeekType, status: Int): List<ClassHomeworkItem> = withContext(Dispatchers.IO) {
        Log.e("XXX", "----------getClassHomeworkStatistical 加载参数-- $dayOfWeek--- $type-- $status--")

        val calendar = Calendar.getInstance()
        calendar.set(Calendar.HOUR_OF_DAY, 0)
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.SECOND, 0)
        //1 周日 2周一 3周二 4周三
        val ofWeek = calendar.get(Calendar.DAY_OF_WEEK)
        if (ofWeek >= 2) {
            calendar.add(Calendar.DAY_OF_YEAR, -(ofWeek - 2))
        } else {
            calendar.add(Calendar.DAY_OF_YEAR, -6)
        }
        calendar.add(Calendar.DAY_OF_YEAR, type.type * 7)

        val (startDate, endDate) = if (dayOfWeek == 0) {
            //全周
            calendar.timeInMillis.toDateYyyyMMddHHmmss() to
                    calendar.also {
                        it.add(Calendar.DAY_OF_YEAR, 6)
                        calendar.set(Calendar.HOUR_OF_DAY, 23)
                        calendar.set(Calendar.MINUTE, 59)
                        calendar.set(Calendar.SECOND, 59)
                    }.timeInMillis.toDateYyyyMMddHHmmss()
        } else {
            calendar.add(Calendar.DAY_OF_YEAR, dayOfWeek - 1)
            calendar.timeInMillis.toDateYyyyMMddHHmmss() to calendar.also {
                calendar.set(Calendar.HOUR_OF_DAY, 23)
                calendar.set(Calendar.MINUTE, 59)
                calendar.set(Calendar.SECOND, 59)
            }.timeInMillis.toDateYyyyMMddHHmmss()
        }
        RestManager.getInstance().classRest().getHomeworkStat(HomeworkStatQuery(1, startDate, endDate, status)).let {
            check(it)
            it.data
        }
    }

    /**
     * 获取班级优秀生
     */
    suspend fun getClassTeacher(): List<Person> = withContext(Dispatchers.IO) {
        RestManager.getInstance().classRest().getTeacherList().let {
            check(it)
            it.data.sortedBy {
                if (it.type == 2) 0 else if (it.type == 3) 1 else 2
            }
        }
    }

    private fun <T> check(it: BaseResponse<T>?) {
        if (!it.isSuccessful && it != null) {
            throw ApiException(it.code, it.msg)
        }
    }

    /**
     * 获取班级优秀生
     */
    suspend fun getClassLeader(): List<Person> = withContext(Dispatchers.IO) {
        RestManager.getInstance().classRest().getStudentList().let {
            check(it)
            it.data.sortedBy {
                if (it.title == "班长") 0 else if (it.title == "副班长") 1 else 2
            }
        }
    }

    /**
     * 获取班级优秀生
     */
    suspend fun getClassExcellentStudents(type: Semester, key: String): List<Person> = withContext(Dispatchers.IO) {
        ClassApi.service.getExcellentStudentList(ExcellentPageQuery(1, type.startDate, key, type.endDate)).let {
            check(it)
            it.data.records
        }
    }

    /**
     * 获取班级通知
     */
    suspend fun getClassHomeworkDetail(id: String, key: String, status: Int) = withContext(Dispatchers.IO) {
        RestManager.getInstance().classRest().getHomeworkUserPage(HomeworkDetailQuery(1, id, key, status)).let {
            check(it)
            it.data
        }
    }

    val classNames = arrayOf("语文", "数学", "英语", "体育", "美术", "道法", "劳动", "音乐", "劳动", "科学")
    val names = arrayOf(
        "张三", "李四", "王五", "赵六", "魏坤", "黄琤琤", "黄玉",
        "吕宫思", "廖舟舟", "利桂瑾", "邱霏霏", "汪及傲", "赵卡", "乔濛濛",
        "姜帝荟", "贾巍巍", "杨访煜", "金米米", "李玟玟", "史安安"
    )
    val homework = arrayOf("作业名称作业名称，过长换行", "周三语文作业", "作业名称作业名称作业名称作业名称备份", "制作一个小风车", "作业名称")
    val rotas = arrayOf("擦玻璃", "倒垃圾", "值日项", "扫地", "擦黑板", "拖地", "倒垃圾")
    val rotasColors = arrayOf(
        "#F24F46",
        "#FF7F17",
        "#FFD000",
        "#1DCF6F",
        "#30BFFF",
        "#306EFF",
        "#6260EB",
        "#F34C88",
        "#C669E8",
        "#B0946C",
        "#7290A6",
        "#CC8B81"
    )
    val tags = arrayOf("团支书", "学习委员", "宣传委员", "体育委员", "生活委员", "纪律委员", "语文课代表", "数学课代表", "英语课代表", "科学课代表", "文艺委员", "道法课代表")

//    private fun mockClassCurriculumItems(): List<ClassDateGroup<ClassCurriculumItem>> {
//        val list = mutableListOf<ClassDateGroup<ClassCurriculumItem>>()
//        for (i in 1..3) {
//            val data = mutableListOf<ClassCurriculumItem>()
//            //星期一的课 假如一天有6节课
//            repeat(8) { it ->
//                (1..7).forEach { dayOfWeek ->
//                    if (dayOfWeek > 5) {
//                        data.add(ClassCurriculumItem.EMPTY)
//                    } else if (it < 6) {
//                        data.add(ClassCurriculumItem(classNames.random(), "", "", teacher = randomTeacher()))
//                    } else {
//                        data.add(ClassCurriculumItem("自习", "", ""))
//                    }
//                }
//            }
//            list.add(ClassDateGroup(i.toLong(), data))
//        }
//
//        return list
//    }

//    private fun mockClassRotaItems(): List<ClassRotaItem> {
//        val data = mutableListOf<ClassRotaItem>()
//        //星期一的课 假如一天有6节课
//        repeat(Random.nextInt(10) + 3) {
//            data += ClassRotaItem(rota = ClassRota(rotas.random(), rotasColors.random()), student = randomTeacher(), hasSign = Random.nextBoolean())
//        }
//
//        return data
//    }
//
//    private fun randomTeacher(type: Int = 0): Person {
//        return Person(
//            name = names.random(),
//            avatar = Random.nextDouble().toString(),
//            no = Random.nextDouble().toString().replace(".", "").take(7),
//            fav = "看书，唱歌，跑步",
//            slogan = "这是一段个人格言，这是一段个人格言，超出这是一段个人格言，这是一段个人格言，超出",
//            specialty = "这是一段个人特长，这是一段个人特长，超出这是一段个人特长，这是一段个人特长，超出",
//            story = "这是一段优秀事迹，这是一段优秀事迹，超出这是一段优秀事迹，这是一段优秀事迹，超出这是一段优秀事迹，这是一段优秀事迹，超出这是一段优秀事迹，这是一段优秀事迹，超出这是一段优秀事迹，这是一段优秀事迹，超出这是一段优秀事迹，这是一段优秀事迹，超出这是一段优秀事迹，这是一段优秀事迹，超出这是一段优秀事迹，这是一段优秀事迹，超出这是一段优秀事迹，这是一段优秀事迹，超出这是一段优秀事迹，这是一段优秀事迹，超出这是一段优秀事迹，这是一段优秀事迹，超出这是一段优秀事迹，这是一段优秀事迹，超出这是一段优秀事迹，这是一段优秀事迹，超出这是一段优秀事迹，这是一段优秀事迹，超出",
//            evaluation = "这是一段班主任评语，文字过长，换行显示这是一段班主任评语，文字过长，换行显示这是一段班主任评语，文字过长，换行显示这是一段班主任评语，文字过长，换行显示这是一段班主任评语，文字过长，换行显示这是一段班主任评语，文字过长，换行显示这是一段班主任评语，文字过长，换行显示这是一段班主任评语，文字过长，换行显示这是一段班主任评语，文字过长，换行显示这是一段班主任评语，文字过长，换行显示",
//            introduce = "这是一段自我介绍，这是一段自我介绍，这是一段自我介绍，这是一段自我介绍，这是一段自我介绍，这是一段自我介绍，这是一段自我介绍，这是一段自我介绍，这是一段自我介300字",
//            tag = if (type == 0) classNames.random() else tags.random(),
//        )
//    }
}